package com.zztl.infiniteBand.net



import com.zztl.infiniteBand.net.imp.DownLoadListener
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException

/**
 * @desc   //添加进度展示
 * @auth ${user}
 * @time 2018/3/16  13:49
 */

class LoadResponseBody(var responseBody: ResponseBody, var loadListener: DownLoadListener) : ResponseBody() {
    private var mBufferedSource: BufferedSource? = null
    private var mResponseBody: ResponseBody
    private var mLoadListener: DownLoadListener?

    init {
        this.mResponseBody = responseBody
        this.mLoadListener = loadListener
    }

    override fun contentType(): MediaType {
        return mResponseBody.contentType()
    }

    override fun contentLength(): Long {
        return mResponseBody.contentLength()
    }

    override fun source(): BufferedSource? {
        if (mBufferedSource == null) {
            mBufferedSource = Okio.buffer(source(mResponseBody.source()))
        }
        return mBufferedSource
    }

    private fun source(source: BufferedSource): Source {
        return object : ForwardingSource(source) {
            internal var totalBytes = 0L

            @Throws(IOException::class)
            override fun read(sink: Buffer, byteCount: Long): Long {
                val bytesRead = super.read(sink, byteCount)
                totalBytes += if (bytesRead == -1L) 0 else bytesRead
                mLoadListener?.apply {
                    if (bytesRead != -1L) {
                        mLoadListener!!.onPregress((totalBytes * 100 / contentLength()).toInt())
                    }
                }
                return bytesRead
            }
        }
    }
}
